import { createRouter, createWebHistory } from 'vue-router'
import BasicLayout from '../components/BasicLayout.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: BasicLayout,
      children: [
        {
          path: '',
          name: 'home',
          component: () => import('../views/HomeView.vue'),
          meta: { title: '首页', keepAlive: true }
        },
        {
          path: 'dashboard',
          name: 'dashboard',
          component: () => import('../views/DashboardView.vue'),
          meta: { title: '控制台', keepAlive: true }
        },
        {
          path: 'profile',
          name: 'profile',
          component: () => import('../views/ProfileView.vue'),
          meta: { title: '个人中心', keepAlive: false }
        },
        {
          path: '/admin/usermanage',
          name: '用户管理',
          component: () => import('@/views/admin/UserManageView.vue')
        },
        {
          path: '/admin/appmanage',
          name: '应用管理',
          component: () => import('@/views/admin/AppManageView.vue'),
          meta: { title: '应用管理', requireAdmin: true }
        },
        {
          path :'/user/login',
          name: '用户登录',
          component: () => import('@/views/user/UserLoginView.vue')
        },
        {
          path : '/user/register',
          name: '用户注册',
          component: () => import('@/views/user/UserRegisterView.vue')
        },
        {
          path: '/chat/:id',
          name: '应用对话',
          component: () => import('@/views/ChatView.vue'),
          meta: { title: '应用对话', keepAlive: false }
        },
        {
          path: '/app/edit/:id',
          name: '编辑应用',
          component: () => import('@/views/AppEditView.vue'),
          meta: { title: '编辑应用', keepAlive: false }
        }
      ]
    }
  ],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 全局前置守卫，设置页面标题
router.beforeEach((to, from, next) => {
  const title = to.meta.title ? `${to.meta.title} - AI Generator` : 'AI Generator'
  document.title = title as string
  next()
})

export default router
